package com.example.hackercore.util;


import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Description：
 *
 * @Author: cw
 * CreateTime：2022-10-10
 */
public class SshGanymedUtil {

    private final static Logger log = LoggerFactory.getLogger(SshGanymedUtil.class);

    public static void connectServer(String ip, int port, String username, String password, String command) {
        Connection conn = new Connection(ip, port);
        Session session = null;
        try {
            conn.connect();
            boolean islogin = conn.authenticateWithPassword(username, password);
            if (islogin) {
                log.info("成功");
            } else {
                log.info("失败");
            }
            session = conn.openSession();
            session.execCommand(command);
            InputStream is = new StreamGobbler(session.getStdout());
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "GBK"));
            String line = reader.readLine();
            while ((line) != null) {
                if (line != null) {
                    System.out.println(line);
                }
            }
        } catch (Exception e) {
            log.error("error", e);
        } finally {
            if (session != null) {
                session.close();
            }
            if (conn != null) {
                conn.close();
            }
        }
    }


}
